
package com.mazaiting.scheduler.runner;

import com.mazaiting.web.holder.SpringContextHolder;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.concurrent.Callable;

/**
 * 执行定时任务
 *
 * @author mazaiting
 * @create_time 2022/4/5 13:11
 */
public class QuartzRunnable implements Callable<Boolean> {
    /**
     * 实体类
     */
    private final Object target;
    /**
     * 方法
     */
    private final Method method;
    /**
     * 参数
     */
    private final String params;

    public QuartzRunnable(String beanName, String methodName, String params)
            throws NoSuchMethodException, SecurityException, ClassNotFoundException {
        // 加载定时任务类
        this.target = SpringContextHolder.getBean(Class.forName(beanName));
        // 复制参数
        this.params = params;
        // 获取方法
        this.method = target.getClass().getMethod(methodName, String.class);
    }

    @Override
    public Boolean call() throws Exception {
        // 允许访问方法
        ReflectionUtils.makeAccessible(method);
        // 调用方法
        return (Boolean) method.invoke(target, params);
    }
}
